package com.woniuxy.ticketmovie.exception;

import com.woniuxy.ticketmovie.entity.ResponseResult;
import org.springframework.dao.DataAccessException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @ClassName TicketExceptionHandler
 * @Description TODO
 * @Author zx
 * @Date 2021-02-24 15:49:21
 * @Version 1.0
 */
@RestControllerAdvice()
public class TicketExceptionHandler {
    @ExceptionHandler(NameExsitException.class)
    public String exceptionHandler(){
        return "异常";
    }

    @ExceptionHandler(DataAccessException.class)
    public ResponseResult<Void> daExceptionHandler(DataAccessException e){
        e.printStackTrace();
        return new ResponseResult(500,"fail");
    }


    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResponseResult<Object> MethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        if (result.hasErrors()) {
//            result.getAllErrors().forEach(c->System.out.println(c.getDefaultMessage()));
            HashMap<String, String> map = new HashMap();
            result.getFieldErrors().forEach(c -> map.put(c.getField(), c.getDefaultMessage()));
            ResponseResult<Object> responseResult = new ResponseResult();
            responseResult.setCode(102);
            responseResult.setMsg("无效参数");
            responseResult.setData(map);
            return responseResult;
//        return new ResponseResult(500,"传入参数有误");
        }
        return null;
    }

    @ExceptionHandler({ConstraintViolationException.class})
    public ResponseResult<Object> MethodArgumentTypeMismatchException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        Map<String, String> map = new HashMap<>();
        //循环进行字符切割put进入map
        constraintViolations.forEach(a-> map.put((a.getPropertyPath()+"").substring((a.getPropertyPath()+"").lastIndexOf(".") + 1),
                a.getMessage()));
            ResponseResult<Object> responseResult = new ResponseResult();
            responseResult.setCode(103);
            responseResult.setMsg("数据有误");
            responseResult.setData(map);
            return responseResult;
    }
}
